<?php

namespace App\Http\Middleware;

use App\Http\Model\Hint;
use App\Http\Model\OutJson;
use App\Http\Model\User;
use App\Http\Services\ContentCheckServices;
use App\Lib\Response;
use Closure;
use Green\Request\V20180509\TextScanRequest;
use Illuminate\Support\Facades\Log;

class SensitiveWordFilteringMiddleware
{
    private $client;
    private $request;
    CONST SCENES = ['antispam'];
    private $contentCheckServices;
    private $requestContent;
    private $userModel;
    private $shumeiFilterConf;
    private $rongFilterConf;

    public function __construct(ContentCheckServices $contentCheckServices)
    {
        $this->contentCheckServices = $contentCheckServices;
        $this->userModel = new User();
        // $this->shumeiFilterConf = config('shumei_filter');
        // $this->rongFilterConf = config('rong_filter');
    }
    
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $this->requestContent = $request;

        /*
        //content 字符串内容校验
        if (is_string($request->input('content'))) {
            if ($content = $request->input('content', '')) {
                $contentJson = json_decode($content, true);
                if ($contentJson && is_array($contentJson) && !empty($contentJson)) {
                    $newContent = [];
                    foreach ($contentJson as $val) {
                        if (isset($val['mess'])) {
                            $this->setContent(['dataId' => $this->getDataId(), 'content' => $val['mess']]);
                            $str = $this->checkContent($val['mess']);
                        }
                        $newContent[] = $val;
                    }
                    $str = json_encode($newContent);
                    if($str) $request->offsetSet('content', $str);
                } else {
                    $this->setContent(['dataId' => $this->getDataId(), 'content' => $content]);
                    $str = $this->checkContent($content);
                    if($str) $request->offsetSet('content', $str);
                }

            }
        } else {
            if ($content = $request->input('content', '')) {
                if (is_array($content) && !empty($content)) {
                    $newContent = [];
                    foreach ($content as $val) {
                        $this->setContent(['dataId' => $this->getDataId(), 'content' => $val['mess']]);
                        $str = $this->checkContent($val['mess']);
                        $newContent[] = $val;
                    }
                    $str = $newContent;
                    if($str) $request->offsetSet('content', $str);
                }
            }
        }
        //Log::debug($request->input('content'));
        if ($content = $request->input('comment_text', '')) {
            $this->setContent(['dataId' => $this->getDataId(), 'content' => $content]);
            $str = $this->checkContent($content);
            if($str) $request->offsetSet('comment_text', $str);
        }
        if ($content = $request->input('reply_text', '')) {
            $this->setContent(['dataId' => $this->getDataId(), 'content' => $content]);
            $str = $this->checkContent($content);
            if($str) $request->offsetSet('reply_text', $str);
        }
        if ($content = $request->input('nickname', '')) {
            $this->setContent(['dataId' => $this->getDataId(), 'content' => $content]);
            $str = $this->checkContent($content);
            if($str) $request->offsetSet('nickname', $str);
        }
        if ($content = $request->input('sign', '')) {
            $this->setContent(['dataId' => $this->getDataId(), 'content' => $content]);
            $str = $this->checkContent($content);
            if($str) $request->offsetSet('sign', $str);
        }
        if ($content = $request->input('name', '')) {
            $this->setContent(['dataId' => $this->getDataId(), 'content' => $content]);
            $str = $this->checkContent($content);
            if($str) $request->offsetSet('name', $str);
        }
        if ($content = $request->input('notice', '')) {
            $this->setContent(['dataId' => $this->getDataId(), 'content' => $content]);
            $str = $this->checkContent($content);
            if($str) $request->offsetSet('notice', $str);
        }
        if ($content = $request->input('desc', '')) {
            $this->setContent(['dataId' => $this->getDataId(), 'content' => $content]);
            $str = $this->checkContent($content);
            if($str) $request->offsetSet('desc', $str);
        }
        if ($content = $request->input('title', '')) {
            $this->setContent(['dataId' => $this->getDataId(), 'content' => $content]);
            $str = $this->checkContent($content);
            if($str) $request->offsetSet('title', $str);
        }
        if ($content = $request->input('condition_msg', '')) {
            $this->setContent(['dataId' => $this->getDataId(), 'content' => $content]);
            $str = $this->checkContent($content);
            if($str) $request->offsetSet('condition_msg', $str);
        }
        if ($content = $request->input('remark_name', '')) {
            $this->setContent(['dataId' => $this->getDataId(), 'content' => $content]);
            $str = $this->checkContent($content);
            if($str) $request->offsetSet('remark_name', $str);
        }
        if ($content = $request->input('txt', '')) {
            $this->setContent(['dataId' => $this->getDataId(), 'content' => $content]);
            $str = $this->checkContent($content);
            if($str) $request->offsetSet('txt', $str);
        }
        if ($content = $request->input('keywords', '')) {
            $this->setContent(['dataId' => $this->getDataId(), 'content' => $content]);
            $str = $this->checkContent($content);
            if ($str != $content){
                $str = '';
            }
            $_POST['keywords'] = $str;
            $_GET['keywords'] = $str;
            $request->offsetSet('keywords', $str);
        }
        */

        return $next($request);
    }
    
    private function init()
    {
        $iClientProfile = \DefaultProfile::getProfile("cn-beijing", config("oss.accesskeyid"), config("oss.accesskeysecret"));
        \DefaultProfile::addEndpoint('cn-beijing', 'cn-beijing', 'Green', "green.cn-beijing.aliyuncs.com");
        $this->client = new \DefaultAcsClient($iClientProfile);
        $this->request = new TextScanRequest();
    }
    
    
    private function setContent($tasks = [])
    {
        return true;
        $tasks = json_encode(['tasks' => $tasks, 'scenes' => self::SCENES, 'bizType' => 'yyaudio']);
        $this->request->setMethod('POST');
        $this->request->setAcceptFormat('JSON');
        $this->request->setContent($tasks);
    }
    
    private function checkContent($str)
    {
        if (empty($str)){
            return;
        }
        # 数美接入
        $checkResult = $this->checkShumeiContent($str);
        # 融云接入
        //$checkResult = $this->checkRongContent($str);
        if (!$checkResult) {
            Response::returnResult(Hint::CONTENT_CHECK_ROBOT_ERR_MSG);
            return;
        }
    }


    private function checkRongContent($content){
        $url = $this->rongFilterConf['apihost'];
        $time = date("Y-m-d H:i:s", time());
        $data['auditId'] = $this->rongFilterConf['auditId'];
        $data['version'] = $this->rongFilterConf['version'];
        $data['timestamp'] = $time;
        $data['bizInfo'] = json_encode([
            "userId" => "-1",
            "msgTime" => $time,
            "ip" => "-1",
            "anchorId" => "-1",
            "liveId" => "-1",
            "msgType" => 0,
            "msgContent" => (string)$content
        ]);

        $str = implode(",", [$data['auditId'], $data['timestamp']]);
        $data['sign'] = base64_encode(hash_hmac("sha1", $str, $this->rongFilterConf['key'], true));

        $ret_data = curl_request($url, $data, 'urlencoded', 'POST');
        $ret_data = json_decode($ret_data, true);

        if ($ret_data['auditResult'] && isset($ret_data['auditResult']['category']) && $ret_data['auditResult']['category'] == 0) {
            return $content;
        }

        return false;
    }

    public function checkShumeiContent($content){
        $url = $this->shumeiFilterConf['apihost'];
        $data['accessKey'] = $this->shumeiFilterConf['accessKey'];
        $data['type'] = $this->shumeiFilterConf['type'];
        $data['appId'] = $this->shumeiFilterConf['appId'];
        $data['organization'] = $this->shumeiFilterConf['organization'];
        $data['data'] = [
            "text" => $content,
            "tokenId" => (string)$this->getDataId()
        ];

        $ret_data = curl_request($url, $data, 'json', 'POST');
        $ret_data = json_decode($ret_data, true);
        if ($ret_data['code'] == 1100 && $ret_data['riskLevel'] && $ret_data['riskLevel'] == "PASS") {
            return $content;
        } else {
            $detail = empty($ret_data['detail']) ? $ret_data : json_decode($ret_data['detail'], true);
            $userInfo = $this->userModel->get_current_user();
            $userId = $userInfo ? $userInfo['user_id'] : 0;
            write_log('word_filter', $this->requestContent->path(), ['api' =>  $this->requestContent->path(), 'user_id' => $userId, 'content' => $this->requestContent->input(), 'ret_data' => $detail, 'time' => date("Y-m-d H:i:s", time()), 'header' =>  $this->requestContent->header()]);
            // if ($detail && isset($detail['filteredText'])) {
            //     return $detail['filteredText'];
            // } else {
            //     return "*";
            // }
            return false;
        }
        return false;
    }
    
    private function getDataId()
    {
        return uniqid();
    }
}
